﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data;
using System.Collections.Generic;
using ConsolidationTool.Common.Entities;
using ConsolidationTool.Common;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint;

namespace ConsolidationTool.WebParts.Flash_Input.Flash_Input_PSRGC.PSRGCEditForm
{
    public partial class PSRGCEditFormUserControl : UserControl
    {
        List<Group> regionGroup = new List<Group>();
        List<Group> subRegionGroup = new List<Group>();
        List<Group> entityGroup = new List<Group>();
        string descriptionHearProduct = string.Empty;
        string descriptionFirstProduct = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string level = getCurUserLevel();
                InitialForm(level);
                InitBaseInfo();
            }
        }
        void InitBaseInfo()
        {
            SPListItem spitem = Title.ListItem;
            lbYear.Text = spitem["Year"].ToString();// Common.BusinessService.GetConfiguration(Constants.Flash_Input_Year);
            lbMonth.Text = spitem["Month"].ToString();// Common.BusinessService.GetConfiguration(Constants.Flash_Input_Month);
            //Headproduct
            DropDownListRGC.DataSource = Common.BusinessService.GetRGCByCategory(Constants.Head_Product);
            DropDownListRGC.DataTextField = "Title";
            DropDownListRGC.DataValueField = "ID";
            DropDownListRGC.DataBind();
            ListItem item = new ListItem("(None)");
            DropDownListRGC.Items.Insert(0, item);
      
            //Firstproduct
            DropDownListFirstRGC.DataSource = Common.BusinessService.GetRGCByCategory(Constants.First_Product);
            DropDownListFirstRGC.DataTextField = "Title";
            DropDownListFirstRGC.DataValueField = "ID";
            DropDownListFirstRGC.DataBind();
            ListItem itemFirstRGC = new ListItem("(None)");
            DropDownListFirstRGC.Items.Insert(0, itemFirstRGC);

            for (int ii = 0; ii < drpRegion.Items.Count; ii++)
            {
                if (drpRegion.Items[ii].Text  == spitem["Region"].ToString())
                {
                    drpRegion.ClearSelection();
                    drpRegion.Items[ii].Selected = true;
                    break;
                }
            }
            BindSubRegion();
            for (int ii = 0; ii < drpSubRegion.Items.Count; ii++)
            {
                if (drpSubRegion.Items[ii].Text == spitem["SubRegion"].ToString())
                {
                    drpSubRegion.ClearSelection();
                    drpSubRegion.Items[ii].Selected = true;
                    break;
                }
            }
            BindEntity();
            for (int ii = 0; ii < drpEntity.Items.Count; ii++)
            {
                if (drpEntity.Items[ii].Value  == spitem["CoCd"].ToString())
                {
                    drpEntity.ClearSelection();
                    drpEntity.Items[ii].Selected = true;
                    break;
                }

            }
            BindEntityInfo();
            BindParentProduct();
        }
        string getCurUserLevel()
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add(Constants.List_Name_Region, "ConsolidationTool_Group");
            dic.Add(Constants.List_Name_SubRegion, "ConsolidationTool_Group");
            dic.Add(Constants.List_Name_Entity, "ConsolidationTool_Group");
            List<Group> groupList = BusinessService.getGroups(dic);
            foreach (Group g in groupList)
            {
                string curUser = SPContext.Current.Web.CurrentUser.LoginName;
                bool result = BusinessService.validateUser(g.groupName, curUser);
                if (result)
                {
                    switch (g.groupLevel)
                    {
                        case Constants.Group_Level_Entity:
                            entityGroup.Add(g);
                            break;
                        case Constants.Group_Level_SubRegion:
                            subRegionGroup.Add(g);
                            break;
                        case Constants.Group_Level_Region:
                            regionGroup.Add(g);
                            break;
                    }
                }
            }
            //Save status
            ViewState["regionGroup"] = regionGroup;
            ViewState["subRegionGroup"] = subRegionGroup;
            ViewState["entityGroup"] = entityGroup;
            //
            string level = string.Empty;
            if (regionGroup.Count > 0)
                level = Constants.Group_Level_Region;
            else if (subRegionGroup.Count > 0)
                level = Constants.Group_Level_SubRegion;
            else if (entityGroup.Count > 0)
                level = Constants.Group_Level_Entity;
            return level;
        }
        void InitialForm(string level)
        {
            List<ListItem> tempList = new List<ListItem>();
            switch (level)
            {
                case Constants.Group_Level_Region:
                    //Get All Region
                    List<Region> rList = BusinessService.getRegion();
                    drpRegion.DataSource = rList;
                    drpRegion.DataValueField = "regionId"; drpRegion.DataTextField = "regionName";
                    drpRegion.DataBind();
                    //Filter Region
                    List<Group> list = (List<Group>)ViewState["regionGroup"];
                    foreach (ListItem item in drpRegion.Items)
                    {
                        string gName = rList.Find(s => s.regionName == item.Text).groupName;
                        Group g = list.Find(s => s.groupName == gName);
                        if (g == null)
                            tempList.Add(item);
                    }
                    //remove item
                    foreach (ListItem item in tempList)
                    {
                        drpRegion.Items.Remove(item);
                    }
                    drpRegion.Items.Insert(0, new ListItem("(None)", "0"));
                    //SubRegion
                    drpSubRegion.Items.Insert(0, new ListItem("(None)", "0"));
                    //Entity
                    drpEntity.Items.Insert(0, new ListItem("(None)", "0"));
                    break;
                case Constants.Group_Level_SubRegion:
                    divRegion.Visible = false;
                    List<SubRegion> sbList = BusinessService.getSubRegion();
                    drpSubRegion.DataSource = sbList;
                    drpSubRegion.DataValueField = "subRegionId"; drpSubRegion.DataTextField = "subRegionName";
                    drpSubRegion.DataBind();
                    //Filter Region
                    List<Group> slist = (List<Group>)ViewState["subRegionGroup"];
                    foreach (ListItem item in drpSubRegion.Items)
                    {
                        string gName = sbList.Find(s => s.subRegionName == item.Text).groupName;
                        Group g = slist.Find(i => i.groupName == gName);
                        if (g == null)
                            tempList.Add(item);
                    }
                    //remove item
                    foreach (ListItem item in tempList)
                    {
                        drpSubRegion.Items.Remove(item);
                    }
                    drpSubRegion.Items.Insert(0, new ListItem("(None)", "0"));
                    drpEntity.Items.Insert(0, new ListItem("(None)", "0"));
                    break;
                case Constants.Group_Level_Entity:
                    divRegion.Visible = false;
                    divSubRegion.Visible = false;
                    List<Entity> enList = BusinessService.getEntity();
                    drpEntity.DataSource = enList;
                    drpEntity.DataValueField = "CoCd"; drpEntity.DataTextField = "entityName";
                    drpEntity.DataBind();
                    //Filter 
                    List<Group> elist = (List<Group>)ViewState["entityGroup"];
                    foreach (ListItem item in drpEntity.Items)
                    {
                        string gName = enList.Find(s => s.CoCd == item.Value).groupName;
                        Group g = elist.Find(i => i.groupName == gName);
                        if (g == null)
                            tempList.Add(item);
                    }
                    //remove item
                    foreach (ListItem item in tempList)
                    {
                        drpEntity.Items.Remove(item);
                    }
                    drpEntity.Items.Insert(0, new ListItem("(None)", "0"));
                    if (drpEntity.Items.Count == 2)
                    {
                        drpEntity.SelectedIndex = 1;
                    }
                    break;
            }
        }

        protected void drpRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindSubRegion();
            BindParentProduct();
        }
        void BindSubRegion()
        {
            drpSubRegion.DataSource = BusinessService.getSubRegion(int.Parse(drpRegion.SelectedValue));
            drpSubRegion.DataValueField = "subRegionId"; drpSubRegion.DataTextField = "subRegionName";
            drpSubRegion.DataBind();
            drpSubRegion.Items.Insert(0, new ListItem("(None)", "0"));
            drpEntity.Items.Clear();
            drpEntity.Items.Insert(0, new ListItem("(None)", "0"));
        }
        void BindEntity()
        {
            drpEntity.DataSource = BusinessService.getEntity(int.Parse(drpRegion.SelectedValue), int.Parse(drpSubRegion.SelectedValue));
            drpEntity.DataValueField = "CoCd"; drpEntity.DataTextField = "entityName";
            drpEntity.DataBind();
            drpEntity.Items.Insert(0, new ListItem("(None)", "0"));
        }
        void BindEntityInfo()
        {
            lbCoCd.Text = drpEntity.SelectedValue;
            lbCompanyFullName.Text = Constants.Company_Name;
        }
        protected void drpSubRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindEntity();
            BindParentProduct();
        }

        protected void drpEntity_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindEntityInfo();
            //divInfo.Attributes["style"] = "font-size: small; width: 800px;";
            BindParentProduct();
        }


        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (drpEntity.SelectedIndex == 0)
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "jsError", "<script>alert('Entity is null');</script>");
                return;
            }
            this.Page.Validate();
            if (Page.IsValid)
            {
                SPListItem item = ConsolidationTool_CoCd.ListItem;

                item["CoCd"] = lbCoCd.Text;
                item["CoFullName"] = lbCompanyFullName.Text;
                item["CoName"] = drpEntity.SelectedItem.Text;
           
                item["Region"] = drpRegion.SelectedItem.Text;
                item["SubRegion"] = drpSubRegion.SelectedItem.Text;

                Title.ItemFieldValue = lbCoCd.Text + "_" + lbYear.Text + lbMonth.Text;
                SaveButton.SaveItem(SPContext.Current, false, string.Empty);


                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList list = web.Lists[Common.Constants.List_Name_HeadProductPSRGC];
                        if (ViewState["RGC"] != null)
                        {
                            Common.BusinessService.DeleteRGCInParentForm(Constants.List_Name_HeadProductPSRGC, drpRegion.SelectedValue, drpSubRegion.SelectedValue, drpEntity.SelectedValue, lbYear.Text);
                            DataTable dtRGC = (DataTable)ViewState["RGC"];
                            for (int ii = 0; ii < dtRGC.Rows.Count; ii++)
                            {
                                SPListItem itHeadProductPSRGC = list.AddItem();
                                itHeadProductPSRGC["Title"] = lbYear.Text + lbMonth.Text + drpEntity.SelectedItem.Text;
                                itHeadProductPSRGC["Region"] = drpRegion.SelectedValue;
                                itHeadProductPSRGC["SubRegion"] = drpSubRegion.SelectedValue;
                                itHeadProductPSRGC["Entity"] = drpEntity.SelectedValue;
                                itHeadProductPSRGC["Qty"] = Convert.ToInt32(dtRGC.Rows[ii]["Qty"].ToString()) + Convert.ToInt32(dtRGC.Rows[ii]["Qty_Current"].ToString());
                                itHeadProductPSRGC["Turnover"] = Convert.ToInt32(dtRGC.Rows[ii]["Turnover"].ToString()) + Convert.ToInt32(dtRGC.Rows[ii]["Turnover_Current"].ToString());
                                itHeadProductPSRGC["ParentForm"] = Title.ListItem.ID;
                                itHeadProductPSRGC["RGC"] = dtRGC.Rows[ii]["ID"].ToString();
                                itHeadProductPSRGC.Update();
                            }
                        }
                        SPList listFirstProduct = web.Lists[Common.Constants.List_Name_FirstProductPSRGC];
                        if (ViewState["FirstRGC"] != null)
                        {
                            Common.BusinessService.DeleteRGCInParentForm(Constants.List_Name_FirstProductPSRGC, drpRegion.SelectedValue, drpSubRegion.SelectedValue, drpEntity.SelectedValue, lbYear.Text);
                            DataTable dtFirstRGC = (DataTable)ViewState["FirstRGC"];
                            for (int ii = 0; ii < dtFirstRGC.Rows.Count; ii++)
                            {
                                SPListItem itFirstProductPSRGC = listFirstProduct.AddItem();
                                itFirstProductPSRGC["Title"] = lbYear.Text + lbMonth.Text + drpEntity.SelectedItem.Text;
                                itFirstProductPSRGC["Region"] = drpRegion.SelectedValue;
                                itFirstProductPSRGC["SubRegion"] = drpSubRegion.SelectedValue;
                                itFirstProductPSRGC["Entity"] = drpEntity.SelectedValue;
                                itFirstProductPSRGC["Qty"] = Convert.ToInt32(dtFirstRGC.Rows[ii]["Qty"].ToString()) + Convert.ToInt32(dtFirstRGC.Rows[ii]["Qty_Current"].ToString());
                                itFirstProductPSRGC["Turnover"] = Convert.ToInt32(dtFirstRGC.Rows[ii]["Turnover"].ToString()) + Convert.ToInt32(dtFirstRGC.Rows[ii]["Turnover_Current"].ToString());
                                itFirstProductPSRGC["ParentForm"] = Title.ListItem.ID;
                                itFirstProductPSRGC["RGC"] = dtFirstRGC.Rows[ii]["ID"].ToString();
                                itFirstProductPSRGC.Update();
                            }
                        }
                    }
                    Utilities.CloseForm();
                }
            }
        }
        protected void btnExit_Click(object sender, EventArgs e)
        {
            Utilities.CloseForm();
        }



        protected void ButtonSave_Click(object sender, EventArgs e)
        {
            if (DropDownListRGC.SelectedIndex == 0)
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "jsError", "<script>alert('RGC is null');</script>");
                return;
            }
            List<RGC> Rgc = new List<RGC>();

            Rgc = Common.BusinessService.GetRGCByID(DropDownListRGC.SelectedValue);
            if (Rgc == null)
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "jsError", "<script>alert('" + DropDownListFirstRGC.SelectedItem.Text + @" is null');</script>");
                return;
            }


            DataTable dtRGC = new DataTable();
            if (ViewState["RGC"] == null)
            {
                dtRGC.Columns.Add("ID");
                dtRGC.Columns.Add("Title");
                dtRGC.Columns.Add("Description");
                dtRGC.Columns.Add("Qty", typeof(float));
                dtRGC.Columns.Add("Turnover", typeof(float));
                dtRGC.Columns.Add("Qty_Current");
                dtRGC.Columns.Add("Turnover_Current");
                ViewState["RGC"] = dtRGC;
            }
            dtRGC = (DataTable)ViewState["RGC"];
            DataView dv = new DataView(dtRGC);
            dv.RowFilter = "ID=" + DropDownListRGC.SelectedValue;
            if (dv.ToTable().Rows.Count > 0)
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "jsError", "<script>alert('" + DropDownListRGC.SelectedItem.Text + " already exists in the list');</script>");
                return;
            }
            DataRow dr = dtRGC.NewRow();
            dr["ID"] = DropDownListRGC.SelectedValue;
            dr["Title"] = DropDownListRGC.SelectedItem.Text;
            dr["Description"] = Rgc[0].Description;
            dr["Qty"] = 0;
            dr["Qty_Current"] = TextBoxQty.Text;
            dr["Turnover"] = 0;
            dr["Turnover_Current"] = TextBoxTurnover.Text;
            dtRGC.Rows.Add(dr);
            dtRGC.DefaultView.AllowEdit = true;
            BindHeadProduct();

            HiddenFieldIfHeadHid.Value = "true";
        }

        protected void DropDownListSubRGC_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void GridViewHeadProduct_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            if (ViewState["RGC"] != null)
            {
                DataTable dt = (DataTable)ViewState["RGC"];
                dt.Rows[e.RowIndex].Delete();
                dt.AcceptChanges();
                BindHeadProduct();
            }
        }
        void BindHeadProduct()
        {
            if (ViewState["RGC"] != null)
            {
                DataTable dt = (DataTable)ViewState["RGC"];
                GridViewHeadProduct.DataSource = dt;
                GridViewHeadProduct.DataBind();
                for (int ii = 0; ii < GridViewHeadProduct.Rows.Count; ii++)
                {
                    GridViewHeadProduct.Rows[ii].Cells[6].Attributes.Add("onclick", "return confirm('Do you want to delete?')");
                }
            }
        }
        void BindFirstProduct()
        {
            if (ViewState["FirstRGC"] != null)
            {
                DataTable dt = (DataTable)ViewState["FirstRGC"];
                GridViewFirstproduct.DataSource = dt;
                GridViewFirstproduct.DataBind();
                for (int ii = 0; ii < GridViewFirstproduct.Rows.Count; ii++)
                {
                    GridViewFirstproduct.Rows[ii].Cells[6].Attributes.Add("onclick", "return confirm('Do you want to delete?')");
                }
            }
        }
        protected void ButtonSave_FirstProduct_Click(object sender, EventArgs e)
        {
            if (DropDownListFirstRGC.SelectedIndex == 0)
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "jsError", "<script>alert('RGC is null');</script>");
                return;
            }
            List<RGC> Rgc = new List<RGC>();

            Rgc = Common.BusinessService.GetRGCByID(DropDownListFirstRGC.SelectedValue);// Common.BusinessService.GetRGCByCategory(Constants.First_Product);
            if (Rgc == null)
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "jsError", "<script>alert('" + DropDownListFirstRGC.SelectedItem.Text + @" is null');</script>");
                return;
            }


            DataTable dtFirstRGC = new DataTable();
            if (ViewState["FirstRGC"] == null)
            {
                dtFirstRGC.Columns.Add("ID");
                dtFirstRGC.Columns.Add("Title");
                dtFirstRGC.Columns.Add("Description");
                dtFirstRGC.Columns.Add("Qty", typeof(float));
                dtFirstRGC.Columns.Add("Turnover", typeof(float));
                dtFirstRGC.Columns.Add("Qty_Current");
                dtFirstRGC.Columns.Add("Turnover_Current");
                ViewState["FirstRGC"] = dtFirstRGC;
            }
            dtFirstRGC = (DataTable)ViewState["FirstRGC"];
            DataView dv = new DataView(dtFirstRGC);
            dv.RowFilter = "ID=" + DropDownListFirstRGC.SelectedValue;
            if (dv.ToTable().Rows.Count > 0)
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "jsError", "<script>alert('" + DropDownListFirstRGC.SelectedItem.Text + " already exists in the list');</script>");
                return;
            }
            DataRow dr = dtFirstRGC.NewRow();
            dr["ID"] = DropDownListFirstRGC.SelectedValue;
            dr["Title"] = DropDownListFirstRGC.SelectedItem.Text;
            dr["Description"] = Rgc[0].Description;
            dr["Qty"] = 0;
            dr["Qty_Current"] = TextBoxQty_Firstproduct.Text;
            dr["Turnover"] = 0;
            dr["Turnover_Current"] = TextBoxTurnover_Firstproduct.Text;
            dtFirstRGC.Rows.Add(dr);
            dtFirstRGC.DefaultView.AllowEdit = true;
            BindFirstProduct();

            HiddenFieldIfFirstHid.Value = "true";
        }

        protected void GridViewFirstproduct_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void GridViewFirstproduct_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            if (ViewState["FirstRGC"] != null)
            {
                DataTable dt = (DataTable)ViewState["FirstRGC"];
                dt.Rows[e.RowIndex].Delete();
                dt.AcceptChanges();
                BindFirstProduct();
            }
        }
        /// <summary>
        /// 邦定历史产品数据
        /// </summary>
        void BindParentProduct()
        {
            List<RGCInParentForm> headProduct = new List<RGCInParentForm>();
            headProduct = Common.BusinessService.GetRGCByParentForm(Constants.List_Name_HeadProductPSRGC, drpRegion.SelectedValue, drpSubRegion.SelectedValue, drpEntity.SelectedValue, lbYear.Text);
            if (headProduct != null)
            {
                DataTable dtRGC = new DataTable();
                dtRGC.Columns.Add("ID");
                dtRGC.Columns.Add("Title");
                dtRGC.Columns.Add("Description");
                dtRGC.Columns.Add("Qty", typeof(float));
                dtRGC.Columns.Add("Turnover", typeof(float));
                dtRGC.Columns.Add("Qty_Current", typeof(float));
                dtRGC.Columns.Add("Turnover_Current", typeof(float));
                foreach (RGCInParentForm hp in headProduct)
                {
                  
                    DataRow drRGC = dtRGC.NewRow();
                    drRGC["ID"] = hp.ID;
                    drRGC["Title"] = hp.Title;
                    drRGC["Description"] = hp.Description;
                    drRGC["Qty"] = hp.Qty;
                    drRGC["Turnover"] = hp.Turnover;
                    drRGC["Qty_Current"] = 0;
                    drRGC["Turnover_Current"] = 0;
                    dtRGC.Rows.Add(drRGC);
                }
                ViewState["RGC"] = dtRGC;
                BindHeadProduct();
            }

            List<RGCInParentForm> firstProduct = new List<RGCInParentForm>();
            firstProduct = Common.BusinessService.GetRGCByParentForm(Constants.List_Name_FirstProductPSRGC, drpRegion.SelectedValue, drpSubRegion.SelectedValue, drpEntity.SelectedValue, lbYear.Text);
            if (firstProduct != null)
            {
                DataTable dtFirstRGC = new DataTable();
                dtFirstRGC.Columns.Add("ID");
                dtFirstRGC.Columns.Add("Title");
                dtFirstRGC.Columns.Add("Description");
                dtFirstRGC.Columns.Add("Qty", typeof(float));
                dtFirstRGC.Columns.Add("Turnover", typeof(float));
                dtFirstRGC.Columns.Add("Qty_Current", typeof(float));
                dtFirstRGC.Columns.Add("Turnover_Current", typeof(float));
                foreach (RGCInParentForm fp in firstProduct)
                {
                  
                    DataRow drFirstRGC = dtFirstRGC.NewRow();
                    drFirstRGC["ID"] = fp.ID;
                    drFirstRGC["Title"] = fp.Title;
                    drFirstRGC["Description"] = fp.Description ;
                    drFirstRGC["Qty"] = fp.Qty;
                    drFirstRGC["Turnover"] = fp.Turnover;
                    drFirstRGC["Qty_Current"] = 0;
                    drFirstRGC["Turnover_Current"] = 0;
                    dtFirstRGC.Rows.Add(drFirstRGC);
                }
                ViewState["FirstRGC"] = dtFirstRGC;
                BindFirstProduct();
            }
        }

        protected void DropDownListFirstRGC_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void DropDownListRGC_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}
